package com.xiaoqiang.MtwV2ForMoblie;

import java.io.File;
import java.io.FileInputStream;
import java.util.Properties;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.provider.Settings;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TabHost;
import android.widget.TabWidget;

import com.xiaoqiang.MtwV2ForMoblie.listener.MyTabChangeListener;
import com.xiaoqiang.MtwV2ForMoblie.update.DownloadDialog;
import com.xiaoqiang.MtwV2ForMoblie.update.InstallApk;
import com.xiaoqiang.MtwV2ForMoblie.update.MtwDownloadApkFileThread;
import com.xiaoqiang.MtwV2ForMoblie.update.UpdateConfirmDialog;
import com.xiaoqiang.layout.login.LoginUIContent;
import com.xiaoqiang.layout.login.LoginUIContentHandlerExtension;
import com.xiaoqiang.layout.mouse.MouseUIContent;
import com.xiaoqiang.network.MySocketClient;
import com.xiaoqiang.util.CrashHandler;
import com.xiaoqiang.util.GetUserNetWorkType;
import com.xiaoqiang.util.Logger;
import com.xiaoqiang.util.MtwDialog;
import com.xiaoqiang.util.MtwDialog.DialogResult;
import com.xiaoqiang.util.MtwDialog.DialogType;
import com.xiaoqiang.util.MtwToast;

public class MainActivity extends Activity {
    
    public final static String MTWVERSION = "1.0.0";
    TabHost tabHost;
    
    public Drawable mtw_logintabonline_select, mtw_logintabonline,
            mtw_logintaboffline_select, mtw_logintaboffline;
    
    public Drawable mtw_commandtab_select, mtw_commandtab;
    
    public Drawable mtw_advancetab_select, mtw_advancetab;
    
    public Drawable mtw_keyboardtab_select, mtw_keyboardtab;
    
    public Drawable mtw_mousetab_select, mtw_mousetab;
    
    public ImageView loginiconView, commandiconView, advancediconView,
            keyboardiconView, mouseiconView;
    
    public String currentTab = "";
    
    public boolean islogin = false;
    
    LinearLayout loginUI, commandUI, advancedUI, keyboardUI, mouseUI;
    
    public MySocketClient mySocketClient;
    
    public static Handler updateLoginUIContenthandler = null;
    
    private static Logger log = new Logger(MainActivity.class);
    
    // 获取服务器配置是否成功
    public boolean getServerConfigisend = false;
    
    // 下载对话框
    public DownloadDialog downloadDialog;
    
    // 下载APK线程
    public MtwDownloadApkFileThread mtwDownloadApkFileThread;
    
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_tab_horizontal);
        CrashHandler crashHandler = CrashHandler.getInstance();
        crashHandler.init(getApplicationContext());
        parseHorizontalTab();
        loginUI = (LinearLayout) this.findViewById(R.id.id_tab_view1);
        commandUI = (LinearLayout) this.findViewById(R.id.id_tab_view2);
        advancedUI = (LinearLayout) this.findViewById(R.id.id_tab_view3);
        keyboardUI = (LinearLayout) this.findViewById(R.id.id_tab_view4);
        mouseUI = (LinearLayout) this.findViewById(R.id.id_tab_view5);
        
        // 添加登陆界面
        LoginUIContent logUiContent = new LoginUIContent(this);
        loginUI.addView(logUiContent.getInitedLoginUIContent(this));
        log.debug("add view logUiContent success!!");
        // 添加鼠標界面
        MouseUIContent mouseUIContent = new MouseUIContent(this);
        mouseUI.addView(mouseUIContent.getInitedMouseUIContent(this));
        log.debug("add view mouseUIContent success!!");
        
        updateLoginUIContenthandler = new LoginUIContentHandlerExtension(logUiContent,
                                                                         this);
        
        verfyUserNetworkType();
        // 程序启动前的动作
        new AppStartAction(this).run();
        
        /*********** 下面为测试代码 *************/
        Button testbuton = (Button) this.findViewById(R.id.testbutton);
        testbuton.setOnClickListener(new TestButtonListener(this));
        
    }
    
    /**
     * 测试用
     */
    class TestButtonListener implements OnClickListener {
        
        Context context;
        
        public TestButtonListener(Context context) {
            this.context = context;
        }
        
        @Override
        public void onClick(View v) {
            MtwDialog m = new MtwDialog(context);
            int sss = GetUserNetWorkType.getAPNType(context);
            MtwDialog.DialogResult result = m.showDialog(MtwDialog.DialogType.Waring,
                                                         "测试网络类型:" + String.valueOf(sss));
            int i = 0;
            i = i / i;
            // 使用Toast来显示异常信息
            new MtwToast(context).show(result.toString(), false);
            try {
                mySocketClient.sendMsg("xiaoqiang");
            }
            catch (Exception e) {
                upataIconSelected("login");
                log.error(e);
            }
        }
    }
    
    private void parseHorizontalTab() {
        // 注意下面的代码用的是android.R.id.tabhost，在布局中有2个ID参数是固定的需要使用固定的ID:
        // 选项卡： TabWidget->android:id/tabs
        // 选项内容：FrameLayout android:id="android:id/tabcontent"
        tabHost = (TabHost) findViewById(R.id.tabHost);
        tabHost.setup();
        mtw_logintabonline_select = this.getResources()
                                        .getDrawable(R.drawable.mtw_logintabonline_select);
        mtw_logintabonline = this.getResources()
                                 .getDrawable(R.drawable.mtw_logintabonline);
        mtw_logintaboffline_select = this.getResources()
                                         .getDrawable(R.drawable.mtw_logintaboffline_select);
        mtw_logintaboffline = this.getResources()
                                  .getDrawable(R.drawable.mtw_logintaboffline);
        
        mtw_commandtab_select = this.getResources()
                                    .getDrawable(R.drawable.mtw_commandtab_select);
        mtw_commandtab = this.getResources()
                             .getDrawable(R.drawable.mtw_commandtab);
        
        mtw_advancetab_select = this.getResources()
                                    .getDrawable(R.drawable.mtw_advancetab_select);
        mtw_advancetab = this.getResources()
                             .getDrawable(R.drawable.mtw_advancetab);
        
        mtw_keyboardtab_select = this.getResources()
                                     .getDrawable(R.drawable.mtw_keyboardtab_select);
        mtw_keyboardtab = this.getResources()
                              .getDrawable(R.drawable.mtw_keyboardtab);
        
        mtw_mousetab_select = this.getResources()
                                  .getDrawable(R.drawable.mtw_mousetab_select);
        mtw_mousetab = this.getResources().getDrawable(R.drawable.mtw_mousetab);
        createHorizontalTab(tabHost);
        tabHost.setOnTabChangedListener(new MyTabChangeListener(this));
    }
    
    private void createHorizontalTab(TabHost tabHost) {
        currentTab = "login";
        View[] loginIndicator = createIndicatorView(this,
                                                    tabHost,
                                                    mtw_logintaboffline_select,
                                                    "login");
        View[] commandIndicator = createIndicatorView(this,
                                                      tabHost,
                                                      mtw_commandtab,
                                                      "command");
        View[] advancedIndicator = createIndicatorView(this,
                                                       tabHost,
                                                       mtw_advancetab,
                                                       "advanced");
        View[] keyboardIndicator = createIndicatorView(this,
                                                       tabHost,
                                                       mtw_keyboardtab,
                                                       "keyboard");
        View[] mouseIndicator = createIndicatorView(this,
                                                    tabHost,
                                                    mtw_mousetab,
                                                    "mouse");
        loginiconView = (ImageView) loginIndicator[1];
        commandiconView = (ImageView) commandIndicator[1];
        advancediconView = (ImageView) advancedIndicator[1];
        keyboardiconView = (ImageView) keyboardIndicator[1];
        mouseiconView = (ImageView) mouseIndicator[1];
        
        tabHost.addTab(tabHost.newTabSpec("login")
                              .setIndicator(loginIndicator[0])
                              .setContent(R.id.id_tab_view1));
        tabHost.addTab(tabHost.newTabSpec("command")
                              .setIndicator(commandIndicator[0])
                              .setContent(R.id.id_tab_view2));
        tabHost.addTab(tabHost.newTabSpec("advanced")
                              .setIndicator(advancedIndicator[0])
                              .setContent(R.id.id_tab_view3));
        tabHost.addTab(tabHost.newTabSpec("keyboard")
                              .setIndicator(keyboardIndicator[0])
                              .setContent(R.id.id_tab_view4));
        tabHost.addTab(tabHost.newTabSpec("mouse")
                              .setIndicator(mouseIndicator[0])
                              .setContent(R.id.id_tab_view5));
        
        TabWidget tw = tabHost.getTabWidget();
        tw.setOrientation(LinearLayout.VERTICAL);// 注意在此处设置此参数 使TAB 垂直布局
    }
    
    /**
     * 创建自定义的 选项卡视图
     * 
     * @param context
     * @param tabHost
     * @param icon
     * @return
     */
    private View[] createIndicatorView(Context context,
                                       TabHost tabHost,
                                       Drawable icon,
                                       String title) {
        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View tabIndicator = inflater.inflate(R.layout.tab_indicator_horizontal,
                                             tabHost.getTabWidget(),
                                             false);
        ImageView iconView = (ImageView) tabIndicator.findViewById(R.id.tabicon);
        // 不设置显示标题
        // final TextView titleView = (TextView)
        // tabIndicator.findViewById(R.id.tabtitle);
        // titleView.setText(title);
        iconView.setImageDrawable(icon);
        return new View[] { tabIndicator, iconView };
    }
    
    /**
     * @function 重置所有tab
     * @param tabname
     *            当前选择的table名称
     */
    public void upataIconSelected(String tabname) {
        tabHost.setCurrentTabByTag(tabname);
        if (tabname == "login") {
            if (islogin) {
                loginiconView.setImageDrawable(mtw_logintabonline_select);
            }
            else {
                loginiconView.setImageDrawable(mtw_logintaboffline_select);
            }
            commandiconView.setImageDrawable(mtw_commandtab);
            advancediconView.setImageDrawable(mtw_advancetab);
            keyboardiconView.setImageDrawable(mtw_keyboardtab);
            mouseiconView.setImageDrawable(mtw_mousetab);
            currentTab = tabname;
        }
        else if (tabname == "command") {
            if (islogin) {
                loginiconView.setImageDrawable(mtw_logintabonline);
            }
            else {
                loginiconView.setImageDrawable(mtw_logintaboffline);
            }
            commandiconView.setImageDrawable(mtw_commandtab_select);
            advancediconView.setImageDrawable(mtw_advancetab);
            keyboardiconView.setImageDrawable(mtw_keyboardtab);
            mouseiconView.setImageDrawable(mtw_mousetab);
            currentTab = tabname;
        }
        else if (tabname == "advanced") {
            if (islogin) {
                loginiconView.setImageDrawable(mtw_logintabonline);
            }
            else {
                loginiconView.setImageDrawable(mtw_logintaboffline);
            }
            commandiconView.setImageDrawable(mtw_commandtab);
            advancediconView.setImageDrawable(mtw_advancetab_select);
            keyboardiconView.setImageDrawable(mtw_keyboardtab);
            mouseiconView.setImageDrawable(mtw_mousetab);
            currentTab = tabname;
        }
        else if (tabname == "keyboard") {
            if (islogin) {
                loginiconView.setImageDrawable(mtw_logintabonline);
            }
            else {
                loginiconView.setImageDrawable(mtw_logintaboffline);
            }
            commandiconView.setImageDrawable(mtw_commandtab);
            advancediconView.setImageDrawable(mtw_advancetab);
            keyboardiconView.setImageDrawable(mtw_keyboardtab_select);
            mouseiconView.setImageDrawable(mtw_mousetab);
            currentTab = tabname;
        }
        else if (tabname == "mouse") {
            if (islogin) {
                loginiconView.setImageDrawable(mtw_logintabonline);
            }
            else {
                loginiconView.setImageDrawable(mtw_logintaboffline);
            }
            commandiconView.setImageDrawable(mtw_commandtab);
            advancediconView.setImageDrawable(mtw_advancetab);
            keyboardiconView.setImageDrawable(mtw_keyboardtab);
            mouseiconView.setImageDrawable(mtw_mousetab_select);
            currentTab = tabname;
        }
    }
    
    /**
     * @funciton 验证用户当前网络环境，并提醒用户前往设置
     */
    private void verfyUserNetworkType() {
        MtwDialog mtwDialog = new MtwDialog(this);
        int i = GetUserNetWorkType.getAPNType(this);
        if (-1 == i) {
            DialogResult result = mtwDialog.showDialog(DialogType.Error,
                                                       this.getResources()
                                                           .getString(R.string.network_error_nothingnetwork));
            if (DialogResult.OK == result) {
                // 进入设置网络设置界面Settings.ACTION_WIRELESS_SETTINGS与ACTION_SETTINGS在4.0中相同，(未知原因)
                startActivity(new Intent(Settings.ACTION_WIRELESS_SETTINGS));
            }
            else {
                // System.exit(0);
            }
        }
        else if (1 != i) {
            DialogResult result = mtwDialog.showDialog(DialogType.Error,
                                                       this.getResources()
                                                           .getString(R.string.network_waring_notwifiwork));
            if (DialogResult.OK == result) {
                // 进入wifi设置界面
                startActivity(new Intent(Settings.ACTION_WIFI_SETTINGS));
            }
            else {
                // System.exit(0);
            }
        }
        
    }
    
    /*
     * 返回按钮提示
     * @see android.app.Activity#onBackPressed()
     */
    @Override
    public void onBackPressed() {
        Activity activity = MainActivity.this;
        while (null != activity.getParent()) {
            activity = activity.getParent();
        }
        DialogResult result = new MtwDialog(activity).showDialog(DialogType.Waring,
                                                                 this.getResources()
                                                                     .getString(R.string.mtw_backbuttonpresstip));
        if (DialogResult.OK == result) {
            super.onBackPressed();
        }
    }
    
    public boolean onCreateOptionsMenu(Menu menu) {
        super.onCreateOptionsMenu(menu);
        MenuInflater inflater = new MenuInflater(getApplicationContext());
        inflater.inflate(R.menu.activity_main, menu);
        return true;
    }
    
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.mtw_menu_about:
                // todo 点击home按钮
                break;
            case R.id.mtw_menu_update:
                if (getServerConfigisend) {
                    Properties mtwinfoProperties = new Properties();
                    try {
                        mtwinfoProperties.load(new FileInputStream(AppStartAction.MTWROOTDIR + "/mtwInfo.properties"));
                    }
                    catch (Exception e) {
                        log.error(e);
                    }
                    String servervesion = mtwinfoProperties.getProperty("MtwVersionServer");
                    if (!MTWVERSION.equals(servervesion)) {
                        if (downloadDialog != null) {
                            downloadDialog.show();
                        }
                        else {
                            String[] mtwUpdateLogarry = mtwinfoProperties.getProperty("MtwUpdateLog")
                                                                         .split("</br>");
                            StringBuilder sb = new StringBuilder();
                            for (String MtwUpdateLog : mtwUpdateLogarry) {
                                sb.append(MtwUpdateLog + "\n");
                            }
                            String mtwUpdateLog = sb.toString();
                            com.xiaoqiang.MtwV2ForMoblie.update.UpdateConfirmDialog.DialogResult result = new UpdateConfirmDialog(this).showDialog(mtwUpdateLog);
                            if (com.xiaoqiang.MtwV2ForMoblie.update.UpdateConfirmDialog.DialogResult.CONFIRM.equals(result)) {
                                downloadDialog = new DownloadDialog(this, this);
                                downloadDialog.show();
                                mtwDownloadApkFileThread = new MtwDownloadApkFileThread(downloadDialog);
                                mtwDownloadApkFileThread.start();
                            }
                        }
                    }
                    else {
                        UpdateConfirmDialog updateConfirmDialog = new UpdateConfirmDialog(this);
                        updateConfirmDialog.setconfirmButtondisenable();
                        updateConfirmDialog.showDialog("");
                    }
                    
                }
                else {
                    UpdateConfirmDialog updateConfirmDialog = new UpdateConfirmDialog(this);
                    updateConfirmDialog.setconfirmButtondisenable();
                    updateConfirmDialog.showDialog("");
                }
                break;
            case R.id.mtw_menu_help:
                // todo 点击help按钮
                break;
            case R.id.mtw_menu_exit:
                onBackPressed();
                // todo 点击exit按钮
                break;
            default:
                // todo 没有点击
                break;
        }
        return super.onOptionsItemSelected(item);
    }
    
    public void installnewAppApk() {
        File apkfile = new File(AppStartAction.MTWROOTDIR + "/MtwV2ForMoblie.apk");
        new InstallApk(this).openFile(apkfile);
    }
}
